const base = {

}

// base.sendAjaxRequest = (url, method, body=null, file=null) => {
//     return new Promise((resolve, reject) => {
        
//         function setHeaders(body) {
//             // Устанавливаем заголовки

//             if (body) {
//                 xhr.setRequestHeader('Content-Type', 'application/json')
//                 xhr.setRequestHeader('X-CSRFToken', body.token)
//             }
//         }

//         function setHeadersForFileTransfer() {
//             // Устанавливаем заголовки для передачи файлов
//         }

//         // ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

//         const xhr = new XMLHttpRequest();
//         xhr.open(method, url);

//         xhr.responseType = 'json';
//         setHeaders(body);

//         xhr.onload = () => {
//             resolve(xhr.response)
//         }

//         if (body) {
//             xhr.send(JSON.stringify(body));
//         } else {
//             xhr.send();
//         }
//     })
// }


base.sendAjaxRequest = (url, method, body=null, file=null) => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open(method, url);

        xhr.responseType = 'json';

        setHeaders(xhr, body, file);
        xhr.onload = () => resolve(xhr.response)
        sendResponse(xhr)
    })


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function sendResponse(xhr) {
        if (body) {
            xhr.send(JSON.stringify(body));
        } else if(file) {
            const formData = new FormData();
            formData.append('file', file.fileData, file.fileName);
            xhr.send(formData);
        } else {
            xhr.send();
        }
    }

    function setHeaders(xhr, body, file) {
        // Устанавливаем заголовки
        
        if(body) {
            xhr.setRequestHeader('X-CSRFToken', body.token);
            xhr.setRequestHeader('Content-Type', 'application/json');
        } else if(file) {
            xhr.setRequestHeader('X-CSRFToken', file.token);
        }
    }
}


base.getCurrentPageNumber = () => {
    // Получаем номер текущей страницы

    return document.querySelector('.current-page').textContent;
}


base.colorPageNotes = (quotes) => {
    // Окрашиваем заметки страницы

    console.log('text', document.querySelector('.text>p'))
    let text = [document.querySelector('.text>p').textContent.replace('  ', ' ')]

    for (let quote of Object.values(quotes)) {
        let modifiedText = text.at(-1).replace(quote.content, `<span style="background: #${quote.color};">${quote.content}</span>`)
        text.push(modifiedText)
    }
    document.querySelector('.text>p').innerHTML = text.at(-1);
}


base.showWindowForDisplayingQuotes = (event) => {
    // Создаем окно для отображения всех цитат

    const $windowForDisplayingQuotesHTML = base.getWindowForDisplayingQuotesHTML();
    document.querySelector('.book-big').insertAdjacentElement('beforeend', $windowForDisplayingQuotesHTML);
    const url = document.location.href + 'quote/'
    base.sendAjaxRequest(url, 'GET')
        .then(result => {
            render(result, $windowForDisplayingQuotesHTML)
        })


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function render(data, $windowForDisplayingQuotesHTML) {

        const csrf_token = data.csrf_token;
        const quotes = data.quotes;

        if (Object.keys(quotes).length == 0) {
            base.showEmptyListOfQuotes();
        } else {
            showListOfQuotes(csrf_token, quotes);
        }

        addColorToQuotes(quotes)
    }


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function showListOfQuotes(csrf_token, quotes) {
        // Показываем список цитат

        for (let quote of Object.values(quotes)) {
            const url = document.location.href + `?page=${quote.page_number}`
            const $quote = `
                <a href="${url}" data-open-quote-in-book="true">
                    <div class="quote-item" data-quote-item-color="${quote.color}">
                        <div class="quote-page-number">${quote.page_number}:</div>
                        <div class="quote-text">&nbsp;${quote.content}</div>
                        <div class="quote-actions">
                            <span class="quote-action note-quote" data-quote-action data-show-quote-note="${quote.id}">
                                <i class="fa-solid fa-note-sticky"></i>
                            </span>
                            <form name="remove-quote">
                                <input type="hidden" name="csrfmiddlewaretoken" value="${csrf_token}">
                                <button type="submit" class="quote-action delete-quote" data-quote-action data-remove-quote="${quote.id}">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </form>
                        </div>
                    </div>
                </a>
            `
            $windowForDisplayingQuotesHTML.querySelector('.all-quotes-window-inner-body .quotes')
                                        .insertAdjacentHTML('beforeend', $quote)
        }
    }


    function addColorToQuotes(quotes) {
        // Добавляем цвет цитатам

        const listOfQoutes = document.querySelectorAll('[data-quote-item-color]');

        for (const quote of listOfQoutes) {
            const colorHEX = quote.dataset.quoteItemColor;
            const colorRGBA = hexToRGBA(`#${colorHEX}`, 0.7);
            quote.style.background = colorRGBA;
        }
    }

    function hexToRGBA(hex, alpha) {
    var r = parseInt(hex.slice(1, 3), 16),
        g = parseInt(hex.slice(3, 5), 16),
        b = parseInt(hex.slice(5, 7), 16);

    if (alpha) {
        return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
    } else {
        return "rgb(" + r + ", " + g + ", " + b + ")";
    }
}
}
base.showEmptyListOfQuotes = () => {
    // Показываем пустой список цитат если их нет

    const listOfQuotes = document.querySelectorAll('.all-quotes-window-wrapper .quote-item')

    if (listOfQuotes.length == 0) {

        document.querySelector('.all-quotes-window-wrapper .quotes').innerHTML = `
            <div class="empty-list-of-quotes">
                Добавленные цитаты будут отображаться здесь...
            </div>
        `
    }
}


base.getWindowForDisplayingQuotesHTML = () => {
    // Получаем окно для отображения цитат в виде HTML

    const basicHtml = `
            <div class="all-quotes-window-inner">
                <div class="all-quotes-window-inner-header">
                    <div class="all-quotes-window-inner-header-title">Цитаты: Мальчик в полосатой пижаме</div>
                    <div class="all-quotes-window-inner-header-close-button" data-close-quotes-window>&times;</div>
                </div>
                <div class="all-quotes-window-inner-body">
                    <div class="quotes">
                    </div>
                </div>
                <div class="all-quotes-window-inner-footer" style="display: none"></div>
            </div>
    `
    const wrapper = document.createElement('div');
    wrapper.className = 'all-quotes-window-wrapper';
    wrapper.insertAdjacentHTML('beforeend', basicHtml);

    return wrapper
}

base.closeWindowForDisplayingQuotes = (event) => {
    const window = document.querySelector('.all-quotes-window-wrapper');
    window.remove();
}

base.getNoteHTML = () => {
    const noteHTML = document.createElement('div');
    noteHTML.className = 'quote-note';
    noteHTML.setAttribute('data-main-quote-note', 'true');
    noteHTML.insertAdjacentHTML('beforeend', `
            <div class="quote-note-text">
            </div>
            <div class="quote-note-actions">
                <span class="quote-note-action close-quote-note" data-close-quote-note="true">
                    <i class="fa-solid fa-xmark"></i>
                </span>
                <span class="quote-note-action edit-quote-note" data-edit-quote-note="true">
                    <i class="fa-solid fa-pen-to-square"></i>
                </span>
                <form name="delete-quote-note">
                    <button type="submit" class="quote-note-action remove-quote-note" data-remove-quote-note="true">
                        <i class="fa-solid fa-trash"></i>
                    </button>
                </form>
            </div>
    `)
    return noteHTML;
}

base.sendRequestToDeleteNote = (token, quoteId) => {
    const url = document.location.href + `note/?delete_note=${quoteId}`;
    base.sendAjaxRequest(url, 'POST', {'token': token})
}

base.removeRelatedNoteHTML = (event) => {
    const nextElement = event.target.closest('a[data-open-quote-in-book]').nextElementSibling;
    if (nextElement && nextElement.hasAttribute('data-main-quote-note')) {
        nextElement.remove();
    }
}

base.isOpenQuotesWindow = () => {
    // Проверяем открыто ли окно для цитат
    return document.querySelector('.all-quotes-window-wrapper');
}


base.indicateReadingStatus = (status) => {
    const readStatusButton = document.querySelector('[data-put-book] span');
    const readStatusInput = document.querySelector('[data-is-read]');

    if (status == 'read') {
        base.addDesiredClassToFinishedBook(readStatusButton, 'read');
        readStatusInput.setAttribute('data-is-read', 'True');
        readStatusInput.innerHTML = 'Прочитана: Да';

    } else if (status == 'unread') {
        base.addDesiredClassToFinishedBook(readStatusButton, 'unread');
        readStatusInput.setAttribute('data-is-read', 'False');
        readStatusInput.innerHTML = 'Прочитана: Нет';
    }
}


base.addDesiredClassToFinishedBook = (element, status) => {
    // Добавляем нужный цвет элементу

    let desiredClass;

    if (status == 'unread') {
        element.previousElementSibling.classList.remove('book-is-read')
        element.classList.remove('book-is-read')
        desiredClass = 'book-is-unread';
    }
    if ( status == 'read') {
        element.previousElementSibling.classList.remove('book-is-unread')
        element.classList.remove('book-is-unread')
        desiredClass = 'book-is-read';
    }

    Array.from(document.querySelector('form[name="finished-book"]').children)
        .forEach(element => {element.classList.add(desiredClass)})
}


base.getWindowForSelectingGroup = () => {
    // Получаем окно для выбора группы
    
    const groupSelectionWindow = document.createElement('div');
    groupSelectionWindow.className = 'group-selection-window';
    const basicHtml = `
        <div class="list-of-groups">
        </div>
    `
    groupSelectionWindow.innerHTML = basicHtml;
    return groupSelectionWindow;
}


base.getCoverSelectionWindow = () => {
    const token = document.querySelector('form>input[name="csrfmiddlewaretoken"]').value;
    const window = document.createElement('div');
    window.className = 'cover-selection-window';
    window.setAttribute('data-temporary-window', 'true')
    window.innerHTML = `
        <form name="change-book-cover" enctype="multipart/form-data">
            <input type="hidden" name="csrfmiddlewaretoken" value="${token}">
            <p class="explanatory-text-of-the-cover">Выберите новую обложку для книги</p>
            <div class="change-book-cover-button">
                <input type="file" data-change-book-cover-button id="input-file">
                <span class="name-of-selected-file">Файл не выбран</span>
                <label for="input-file" data-choose-book-cover>
                    <i class="fa-solid fa-download"></i>
                    <span>Выбрать</span>
                </label>
            </div>
            <div>
                <button type="submit" data-change-book-cover>Изменить обложку</button>
            </div>
        </form>
    `
    return window;
}